package com.example.pc.videodemo.ThreadPool

import java.util.concurrent.*

class ThreadPoolProxy constructor(var mCorePoolSize: Int, var mMaximumPoolSize: Int, var mKeepAliveTime: Long) {
    private var mExecutor // 只需创建一次
            : ThreadPoolExecutor? = null

    private fun initThreadPoolExecutor(): ThreadPoolExecutor? {
        if (mExecutor == null) {
            synchronized(ThreadPoolProxy::class.java, {
                if (mExecutor == null) {
                    val unit: TimeUnit = TimeUnit.MILLISECONDS
                    val workQueue: BlockingQueue<Runnable> = LinkedBlockingQueue() // 无界队列
                    val threadFactory: ThreadFactory = Executors.defaultThreadFactory()
                    val handler: RejectedExecutionHandler = ThreadPoolExecutor.AbortPolicy() // 丢弃任务并抛出RejectedExecutionException异常。
                    mExecutor = ThreadPoolExecutor( //
                            mCorePoolSize,  // 核心的线程数
                            mMaximumPoolSize,  // 最大的线程数
                            mKeepAliveTime,  // 保持时间
                            unit,  // 保持时间对应的单位
                            workQueue,  // 缓存队列/阻塞队列
                            threadFactory,  // 线程工厂
                            handler // 异常捕获器
                    )
                }
            })
        }
        return mExecutor
    }

    /** 执行任务  */
    fun execute(task: Runnable?) {
        initThreadPoolExecutor()
        mExecutor?.execute(task)
    }

    /** 提交任务  */
    fun submit(task: Runnable?): Future<*>? {
        initThreadPoolExecutor()
        return mExecutor?.submit(task)
    }

    /** 移除任务  */
    fun removeTask(task: Runnable?) {
        initThreadPoolExecutor()
        mExecutor?.remove(task)
    }
}